package com.itheima.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.entity.User;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter("/*")
public class LoginCheckFilter implements Filter {

    /**
     * AntPathMatcher  路径匹配器
     */
    public static final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        String requestURI = request.getRequestURI();
        String[] urls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/user/sendMsg",
                "/user/login",
                "/front/**"
        };

        boolean flag = check(urls, requestURI);
        if (flag) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }


        //判断是否登陆
        Long employee = (Long) request.getSession().getAttribute("employee");
        if (employee != null) {
            //走到这里 表示已登录 把id放放到ThreadLocal里面
            //ThreadLocal 封装工具类  字段填充 获取当前用户id
            BaseContext.setCurrentId(employee);

            filterChain.doFilter(servletRequest, servletResponse);
            //响应之前删除存储数据
            BaseContext.remove();
            return;
        }

        User user = (User) request.getSession().getAttribute("user");
        if(user!=null){
            BaseContext.setCurrentId(user.getId());
            filterChain.doFilter(servletRequest, servletResponse);
            BaseContext.remove();//在响应之前删除存储数据
            return;
        }

        R<Object> notlogin = R.error("NOTLOGIN");
        ObjectMapper mapper = new ObjectMapper();
        String string = mapper.writeValueAsString(notlogin);
        servletResponse.getWriter().write(string);

    }

    private boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = antPathMatcher.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
